package com.dao.Impl;

import com.dao.StockDao;
import com.entity.Goods;
import com.entity.PageBean;
import com.entity.Stock;
import com.util.JDBC;
import com.util.TransBean;

import java.util.List;
import java.util.Map;

/**
 * @author 沐白
 */

public class StockDaoImpl implements StockDao {
    @Override
    public int addStock(Stock stock) {
        int stockId = (int) JDBC.selectArray("select max(id) from stock").get(0).get(0) + 1001;
        int i = JDBC.sqlUpdate("insert into stock(stockId,staffId,stockTime,count,goodsId,momo) values(?,?,now(),?,?,?)",
                stockId, stock.getStaffId(), stock.getCount(), stock.getGoodsId(), stock.getMomo());

        if (i != -1) {
            return JDBC.sqlUpdate("update goods set code=code-? where id=?",stock.getCount(), stock.getGoodsId());
        }
        return -1;
    }

    @Override
    public void findByPage(PageBean page) {

        String sql = ("select count(*) from stock,goods,category,staff where stock.goodsId = goods.id and goods.categoryId = category.id and staff.staffId = stock.staffId ");
        if (page.getFactor() != null) {
            sql += page.getFactor()[0];
        }
        List<List> lists = JDBC.selectArray(sql);
        page.setRowCount(((Long) lists.get(0).get(0)).intValue());
        page.setTotalPage();
        page.setStartIndex();
        sql = ("select stock.id, stockId, staffName, stockTime, stock.count,goods.id goodsId, goods.name goodsName, category.name cgName from stock,goods,category,staff where stock.goodsId = goods.id and goods.categoryId = category.id and staff.staffId = stock.staffId ");
        if (page.getFactor() != null) {
            sql += page.getFactor()[0];
        }
        sql += " limit ?,?";
        List<Map> map = JDBC.selectMap(sql, page.getStartIndex(), page.getPageSize());
        page.setData(map);
    }

    @Override
    public int modifyStock(Stock stock) {
        int i = JDBC.sqlUpdate("update stock set count=? where stockId=?", stock.getCount(), stock.getStockId());
        System.out.println(stock);

        if (i != -1) {
            return JDBC.sqlUpdate("update goods set code=code+? where id=?", stock.getCount() - stock.getStaffId(), stock.getGoodsId());
        }
        return -1;
    }

    @Override
    public int delStock(Integer id) {
        return JDBC.sqlUpdate("delete from stock where id=?", id);
    }
}
